var aardvarkPicsaveNS=function(c,f,b){var e=c.split(f||"."),g=b||window,d,a;for(d=0,a=e.length;d<a;d++){g=g[e[d]]=g[e[d]]||{}}return g};

aardvarkPicsaveNS("com.aardvarkPicsave.tools");

com.aardvarkPicsave.tools = function() {

	var pub = {};
	
	pub.bundle = null;
	pub.uploadingTitle = null;
	pub.dimensions = null;
	pub.filesize = null;
	pub.imgUrl = '';
	pub.areaStartX = 0;
	pub.areaStartY = 0;
	pub.areaEndX = 250;
	pub.areaEndY = 250;
	pub.areaMoveX = 0;
	pub.areaMoveY = 0;
	pub.areaDrag = false;
	pub.areaMoving = false;
	pub.areaResize = false;
	pub.areaSelectedTab = -1;
	pub.selectingArea = 0;
	pub.apiUrl = null;
	pub.apiDomain = null;

	pub.srGetStrBundle = function(path) {

		var strBundle = null;

		var bundleService = Components.classes["@mozilla.org/intl/stringbundle;1"].getService();
		bundleService = bundleService.QueryInterface(Components.interfaces.nsIStringBundleService);

		strBundle = bundleService.createBundle(path);

		return strBundle;

	};

	

	pub.fullPage = function() {

		var h = 0;
		var h2 = 0;
		var w = 0;
		var w2 = 0;

		var doc = document.commandDispatcher.focusedWindow;
		var doc2 = window.content;

		if (doc.document.compatMode == "CSS1Compat") {

			h = doc.document.documentElement.scrollHeight;
			h2 = doc2.document.documentElement.scrollHeight;
			w = doc.document.documentElement.scrollWidth;
			w2 = doc2.document.documentElement.scrollWidth;

		} else {

			h = doc.document.body.scrollHeight;
			h2 = doc2.document.body.scrollHeight;
			w = doc.document.body.scrollWidth;
			w2 = doc2.document.body.scrollWidth;

		};

		if (h2 > h && w2 > w) {

			h = h2;
			w = w2;
			doc = doc2;

		};
		
		pub.capture(doc,0,0,w,h);

	};

	pub.visible = function() {

		var x = window.content.scrollX;
		var y = window.content.scrollY; 
		var h = 0;
		var w = 0;

		if (window.content.document.compatMode == "CSS1Compat") {

			h = window.content.document.documentElement.clientHeight;
			w = window.content.document.documentElement.clientWidth;

		} else {

			h = window.content.document.body.clientHeight;
			w = window.content.document.body.clientWidth;

		};
		
		pub.capture(window.content,x,y,w,h);

	};

	pub.capture = function(win, x, y, w, h) {		
		const MAX_DIM = 15360;
		var canvasW = w;
		var canvasH = h;

		if ( w > MAX_DIM || h > MAX_DIM ) {

			if ( w > h ) {

				canvasW = MAX_DIM;
				canvasH = canvasW*h/w;

			} else {

				canvasH = MAX_DIM;
				canvasW = canvasH*w/h;

			};

		};

		var canvas = document.createElementNS('http://www.w3.org/1999/xhtml','canvas');
		canvas.style.width = canvasW+"px";
		canvas.style.height = canvasH+"px";
		canvas.width = canvasW;
		canvas.height = canvasH;

		var ctx = canvas.getContext("2d");
		ctx.clearRect(0, 0, canvasW, canvasH);
		ctx.save();
		ctx.scale(canvasW/w, canvasH/h);
		ctx.drawWindow(win, x, y, w, h, "rgb(255,255,255)");
		ctx.restore();

		return pub.preferences(canvas);
		
	};

	pub.preferences = function(canvas) {

		var doc = window.content.document;

		var bod = doc.getElementsByTagName('body')[0];

		var shadow = doc.createElement('div');
		shadow.id = 'picsave-overlay-shadow';
		shadow.style.opacity = "0.7";
		shadow.style.MozOpacity = shadow.style.opacity;
		shadow.style.top="0";
		shadow.style.left="0";
		shadow.style.width="100%";
		shadow.style.height="100%";
		shadow.style.display="block";
		shadow.style.position="fixed";
		shadow.style.backgroundColor="#000";
		shadow.style.zIndex = "9996";
		bod.appendChild(shadow);

		window.openDialog("chrome://picsave/content/picsaveUploadPreferences.xul", "picsaveUploadPreferences", "centerscreen,chrome,modal", canvas);

	};
	
	pub.captureUpload = function(canvas,mimeType,quality,sfw,image_name,ext,father) {

		const MULTI						= "@mozilla.org/io/multiplex-input-stream;1";
		const STRINGIS					= "@mozilla.org/io/string-input-stream;1";
		const IOSVC						= "@mozilla.org/network/io-service;1"
		const nsIMultiplexInputStream	= Components.interfaces.nsIMultiplexInputStream;
		const nsIStringInputStream		= Components.interfaces.nsIStringInputStream;
		const nsIIOService				= Components.interfaces.nsIIOService
		const BOUNDARY					= "345823569845694578678";

		var url = canvas.toDataURL(mimeType,quality);

		var email;
		var password;
		var gallery_title;

		var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);

		if (prefs.getPrefType("extensions.picsave.prefs.email") == prefs.PREF_STRING) {
			email = prefs.getCharPref("extensions.picsave.prefs.email");
		};

		if (email!='') {

			var PMhostname = 'chrome://picsave';
			var PMformSubmitURL = 'Account Info';
			var password = '';

			try {

				if ("@mozilla.org/passwordmanager;1" in Components.classes) {

					try {

						var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"].getService(Components.interfaces.nsIPasswordManager);

						var e = passwordManager.enumerator;

						while (e.hasMoreElements()) {

							try {
							
								var pass = e.getNext().QueryInterface(Components.interfaces.nsIPassword);
								if (pass.host == PMhostname && pass.user == email) {

									password = pass.password;
									break;

								};
								
							} catch (ex) { };

						};


					} catch(ex) { };

				} else if ("@mozilla.org/login-manager;1" in Components.classes) {

					var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
					var logins = passwordManager.findLogins({}, PMhostname, PMformSubmitURL, null);
	  
					for (var i = 0; i < logins.length; i++) {

						if (logins[i].username == email) {

							password = logins[i].password;
							break;

						};

					};

				};

			} catch(ex) { };

		};

		if (password!='') {

			var str = 'sess_picsave_'+password+'y';
			var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);

			converter.charset = "UTF-8";  
			var result = {};  
			var data = converter.convertToByteArray(str, result);  
			var ch = Components.classes["@mozilla.org/security/hash;1"].createInstance(Components.interfaces.nsICryptoHash);
			ch.init(ch.MD5);  
			ch.update(data, data.length);  
			var hash = ch.finish(false);  

			function toHexString(charCode) {
				return ("0" + charCode.toString(16)).slice(-2);
			};

			function ahex(i) {

				if (!isNaN(i)) {

					return toHexString(hash.charCodeAt(i))
					
				};
				
			};

			var passwordmd5 = [ahex(i) for (i in hash)].join("");  

		};

		if (prefs.getPrefType("extensions.picsave.prefs.gallery_title") == prefs.PREF_STRING) {
			gallery_title = prefs.getCharPref("extensions.picsave.prefs.gallery_title");
		};

		var header = new String();
		header += "\r\n";
		header += "--" + BOUNDARY + "\r\n";
		header += "Content-disposition: form-data;name=\"f\"\r\n\r\nupload\r\n";
		header += "--" + BOUNDARY + "\r\n";
		header += "Content-disposition: form-data;name=\"st\"\r\n\r\n1\r\n";
		header += "--" + BOUNDARY + "\r\n";
		if (email!='' && password!='') {
			header += "Content-disposition: form-data;name=\"e\"\r\n\r\n"+email+"\r\n";
			header += "--" + BOUNDARY + "\r\n";
			header += "Content-disposition: form-data;name=\"p\"\r\n\r\n"+passwordmd5+"\r\n";
			header += "--" + BOUNDARY + "\r\n";
		};
		if (gallery_title!='') {
			header += "Content-disposition: form-data;name=\"ugt\"\r\n\r\n"+gallery_title+"\r\n";
			header += "--" + BOUNDARY + "\r\n";
		};
		var referer_ = window.content.document.location;
		header += "Content-disposition: form-data;name=\"r\"\r\n\r\n"+escape(referer_)+"\r\n";
		header += "--" + BOUNDARY + "\r\n";
		header += "Content-disposition: form-data;name=\"sfw\"\r\n\r\n"+sfw+"\r\n";
		header += "--" + BOUNDARY + "\r\n";
		header += "Content-disposition: form-data;name=\"image_name\"\r\n\r\n"+escape(image_name)+"\r\n";
		header += "--" + BOUNDARY + "\r\n";
		header += "Content-disposition: form-data;name=\"_file\";filename=\"snapshot"+ext+"\"\r\n";
		header += "Content-Type: "+mimeType+"\r\n";
		header += "\r\n";
		var header_stream = Components.classes[STRINGIS].createInstance(nsIStringInputStream);
		header_stream.setData(header, header.length);

		var io = Components.classes[IOSVC].getService(nsIIOService);
		var channel = io.newChannelFromURI( io.newURI(url, "UTF8", null) );
		var data_stream = channel.open();

		var end_stream = Components.classes[STRINGIS].createInstance(nsIStringInputStream);
		var bs = new String("\r\n--" + BOUNDARY + "--\r\n");
		end_stream.setData(bs, bs.length);

		var filesize = 0;

		var mux_stream = Components.classes[MULTI].createInstance(nsIMultiplexInputStream);
		mux_stream.appendStream(header_stream);
		filesize = mux_stream.available();
		mux_stream.appendStream(data_stream);
		filesize = mux_stream.available()-filesize;
		mux_stream.appendStream(end_stream);

		var req = new XMLHttpRequest();
		req.open('POST', pub.apiUrl, true);
		req.onreadystatechange = function(){ pub.captureUploadState(req,father); };
		req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		req.setRequestHeader("Content-Length", mux_stream.available() );
		req.send(mux_stream);

		pub.showUploading(father,canvas.width,canvas.height,filesize);

	};

	pub.captureUploadState = function(req,father) {

		if ( req.readyState == 4 ) {

			if ( req.status == 200 ) {

				result = req.responseText;
				
				result = eval("("+result+")");
				var tabsMode;

				var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);

				if (prefs.getPrefType("extensions.picsave.prefs.loadLocation") == prefs.PREF_INT) {
					tabsMode = prefs.getIntPref("extensions.picsave.prefs.loadLocation");
				};
				
				

				pub.hideUploading(father);

				if (father.getElementById('picsave-overlay-shadow')) {
					
					father.getElementById('picsave-overlay-shadow').parentNode.removeChild(father.getElementById('picsave-overlay-shadow'));

				};
				if(result.status==0){
					alert(result.err);
				}else{

// switch(tabsMode) {
// case 0:
// myTabRef = getBrowser().selectedTab;
// var tabBr = getBrowser().getBrowserForTab(myTabRef);
// var doc = tabBr.contentDocument;
// break;
// case 1:
// myTabRef = getBrowser().addTab();
// getBrowser().selectedTab = myTabRef;
// var tabBr = getBrowser().getBrowserForTab(myTabRef);
// var doc = tabBr.contentDocument;
// break;
// case 2:
// window.open();
// var wm =
// Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
// var doc =
// wm.getMostRecentWindow("navigator:browser").getBrowser().contentDocument;
// break;
// case 3:
// myTabRef = getBrowser().addTab();
// var tabBr = getBrowser().getBrowserForTab(myTabRef);
// var doc = tabBr.contentDocument;
// break;
// default:
// window.open();
// var wm =
// Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
// var doc =
// wm.getMostRecentWindow("navigator:browser").getBrowser().contentDocument;
// break;
// };

					// doc.location = result.pic;
					// window.openDialog("chrome://picsave/content/showPicture.xul",
					// "show_picture",
					// "centerscreen,chrome,modal,resizable",result.pic,result.width,result.height);
					pub.imgShow(father,result.pic,result.width,result.height);
				}

			} else {

				alert('There was a problem with the request\nstatus=' + req.status);

			};

		};

	};

	pub.imgShow = function(doc,src,width_,height_) {		
		if(doc.getElementById('picsave-overlay-show')){// 判断
			pub.picHide(doc);
		}
		var base = 600;
		if(width_>height_){
	   		width = width_>base?base:width_;
	   		height = height_*width/width_;	   		
	   }else{	   	
	   		height = height_>base?base:height_;	   		
	   		width = width_*height/height_;
	   }
	   
		var bod = doc.getElementsByTagName('body')[0];

		var uploading_img = doc.createElement('img');
		uploading_img.src = src;
		uploading_img.id = 'uploading_img';
		uploading_img.style.margin = "0px auto 0px auto";
		uploading_img.style.width=width+"px";
		uploading_img.style.height=height+"px";
		uploading_img.style.display="block";
		uploading_img.style.lineHeight="1.2em";
		uploading_img.style.zIndex="1";

		var close_img = doc.createElement('img');
		close_img.src = pub.apiDomain+"api/image/api-close.jpg";
		close_img.id = 'close_img';
		close_img.style.margin = "2px 2px 0px 0";
		close_img.style.width="15px";
		close_img.style.height="15px";
		close_img.style.display="block";
		close_img.style.position="absolute";
		close_img.style.right="0";
		close_img.style.top="0";
		close_img.style.zIndex="999";
		close_img.style.cursor="pointer";
		close_img.style.lineHeight="1.2em";
		
		close_img.addEventListener("click", function(){// 点击关闭
			doc.getElementById('picsave-overlay-show').parentNode.removeChild(doc.getElementById('picsave-overlay-show')); 
		}, true);		
		var count = 0;
		window.addEventListener("keyup",  function(e){// 点击关闭
			if(e.keyCode==27){// ESC键盘关闭
				doc.getElementById('picsave-overlay-show').parentNode.removeChild(doc.getElementById('picsave-overlay-show')); 				
			}
// else if(e.keyCode==13&&count==0){
// count++;
// myTabRef_ = getBrowser().addTab();
// var tabBr_ = getBrowser().getBrowserForTab(myTabRef_);
// var doc_ = tabBr_.contentDocument;
// doc_.location = src;
// doc.getElementById('picsave-overlay-show').parentNode.removeChild(doc.getElementById('picsave-overlay-show'));
// //window.removeEventListener("keyup",funtion(){},false);
// }
		}, false);
		var uploading = doc.createElement('iframe');
		uploading.id = 'picsave-overlay-show';
		uploading.style.top="50%";
		uploading.style.left="50%";
		uploading.style.border="0";
		uploading.style.margin = "-"+(height/2)+"px 0 0 -"+(width/2)+"px";
		uploading.style.backgroundColor="#FFFFFF";
		uploading.style.width=width+"px";
		uploading.style.height=height+"px";
		uploading.style.display="block";
		uploading.style.border="3px solid #AB4EFF";
		uploading.style.position="fixed";
		uploading.style.zIndex = "9998";
		bod.appendChild(uploading);
		setTimeout(function() {
			doc.getElementById('picsave-overlay-show').contentDocument.body.style.padding="0px 0 0 0";
			doc.getElementById('picsave-overlay-show').contentDocument.body.style.margin="0px 0 0 0";
			doc.getElementById('picsave-overlay-show').contentDocument.body.style.textAlign = "center";
			doc.getElementById('picsave-overlay-show').contentDocument.body.appendChild(close_img);
			doc.getElementById('picsave-overlay-show').contentDocument.body.appendChild(uploading_img);
		}, 100);
		
// setTimeout(function() {
// pub.picHide(doc);
// }, 10000);
	};

	pub.picHide = function(doc) {
		doc.getElementById('picsave-overlay-show').parentNode.removeChild(doc.getElementById('picsave-overlay-show')); 

	};
	pub.showUploading = function(doc,width,height,weight) {

		var bod = doc.getElementsByTagName('body')[0];

		var uploading_img = doc.createElement('img');
		uploading_img.src = pub.apiDomain+"api/image/ext_img_uploading.gif";
		uploading_img.id = 'uploading_img';
		uploading_img.style.margin = "0 auto 8px auto";
		uploading_img.style.width="25px";
		uploading_img.style.height="25px";
		uploading_img.style.display="block";
		uploading_img.style.lineHeight="1.2em";

		var uploadingText = doc.createElement('div');
		uploadingText.style.lineHeight="1.2em";
		uploadingText.style.margin="0";
		uploadingText.style.padding="0";
		uploadingText.style.color="#000000";
		uploadingText.innerHTML = "<span style=\"font-weight: bold;font-size: 16px;\">"+pub.uploadingTitle+"</span><br /><br /><u>"+pub.dimensions+":</u> "+width+" x "+height+"<br /><u>"+pub.filesize+":</u> "+(weight>0?(Math.round(weight/1024 * 100) / 100)+"Kb":"未知");

		var uploading = doc.createElement('iframe');
		uploading.id = 'picsave-overlay-uploading';
		uploading.style.top="50%";
		uploading.style.left="50%";
		uploading.style.border="0";
		uploading.style.margin = "-45px 0 0 -100px";
		uploading.style.backgroundColor="#FFFFFF";
		uploading.style.width="200px";
		uploading.style.height="125px";
		uploading.style.display="block";
		uploading.style.position="fixed";
		uploading.style.zIndex = "9998";
		bod.appendChild(uploading);
		setTimeout(function() {

			doc.getElementById('picsave-overlay-uploading').contentDocument.body.style.padding="10px 0 0 0";
			doc.getElementById('picsave-overlay-uploading').contentDocument.body.style.fontFamily="Verdana";
			doc.getElementById('picsave-overlay-uploading').contentDocument.body.style.fontSize="12px";
			doc.getElementById('picsave-overlay-uploading').contentDocument.body.style.textAlign = "center";
			doc.getElementById('picsave-overlay-uploading').contentDocument.body.style.lineHeight="1.2em";
			doc.getElementById('picsave-overlay-uploading').contentDocument.body.appendChild(uploading_img);
			doc.getElementById('picsave-overlay-uploading').contentDocument.body.appendChild(uploadingText);

		}, 100);
      
	};

	pub.hideUploading = function(doc) {

		doc.getElementById('picsave-overlay-uploading').parentNode.removeChild(doc.getElementById('picsave-overlay-uploading')); 

	};

	pub.areaCreate = function() {

		var ownerDocument = window.top.getBrowser().selectedBrowser.contentDocument;

		var areaProtector = ownerDocument.createElement('div');
		areaProtector.id = 'picsave-area-protector';
		areaProtector.style.top="0";
		areaProtector.style.left="0";
		areaProtector.style.width="100%";
		areaProtector.style.height="100%";
		areaProtector.style.display="block";
		areaProtector.style.position="fixed";
		areaProtector.style.zIndex = "9995";
		ownerDocument.body.appendChild(areaProtector);

		var areaElement = ownerDocument.createElement("div");
		areaElement.setAttribute("id", "picsaveArea");
		areaElement.style.zIndex = "9998";
		ownerDocument.body.appendChild(areaElement);

		var containerElement = ownerDocument.createElement("div");
		containerElement.setAttribute("id", "picsaveArea-container");
		containerElement.style.zIndex = "9997";
		areaElement.appendChild(containerElement);

		var resizeElement    = ownerDocument.createElement("div");
		resizeElement.setAttribute("id", "picsaveArea-north-west");
		resizeElement.style.zIndex = "9997";
		containerElement.appendChild(resizeElement);

		resizeElement = ownerDocument.createElement("div");
		resizeElement.setAttribute("id", "picsaveArea-north-east");
		resizeElement.style.zIndex = "9997";
		containerElement.appendChild(resizeElement);

		resizeElement = ownerDocument.createElement("div");
		resizeElement.setAttribute("id", "picsaveArea-south-east");
		resizeElement.style.zIndex = "9997";
		containerElement.appendChild(resizeElement);

		resizeElement = ownerDocument.createElement("div");
		resizeElement.setAttribute("id", "picsaveArea-south-west");
		resizeElement.style.zIndex = "9997";
		containerElement.appendChild(resizeElement);

		var styleElement = ownerDocument.createElement("style");
		styleElement.setAttribute("id", "picsaveArea-styles");
		styleElement.setAttribute("type", "text/css");
		styleElement.appendChild(ownerDocument.createTextNode("* { cursor: crosshair !important; }"));
		styleElement.appendChild(ownerDocument.createTextNode("#picsaveArea { -moz-opacity: 0.5 !important; -moz-outline: 1px solid #ff0000 !important; background-color: #cccccc !important; border-style: none !important; height: "+(pub.areaEndY-pub.areaStartY)+"px; left: "+pub.areaStartX+"px; margin: 0 !important; opacity: 0.5 !important; outline: 1px solid #ff0000 !important; padding: 0 !important; position: absolute !important; top: "+pub.areaStartY+"px; width: "+(pub.areaEndX-pub.areaStartX)+"px; z-index: 9999 !important; }"));
		styleElement.appendChild(ownerDocument.createTextNode("#picsaveArea > div > div { background-color: #666666 !important; border-color: #ff0000 !important; border-style: solid !important; height: 15px !important; margin: 0 !important; padding: 0 !important; position: absolute !important; width: 15px !important; }"));
		styleElement.appendChild(ownerDocument.createTextNode("#picsaveArea-container { border-style: none !important; cursor: move !important; height: 100% !important; margin: 0 !important; overflow: hidden !important; padding: 0 !important; position: relative !important; width: 100% !important; }"));
		styleElement.appendChild(ownerDocument.createTextNode("#picsaveArea-north-east { border-width: 0 0 1px 1px !important; cursor: ne-resize !important; right: 0 !important; top: 0 !important; } #picsaveArea-north-west { border-width: 0 1px 1px 0 !important; cursor: nw-resize !important; left: 0 !important; top: 0 !important; } #picsaveArea-south-east { border-width: 1px 0 0 1px !important; bottom: 0 !important; cursor: se-resize !important; right: 0 !important; } #picsaveArea-south-west { border-width: 1px 1px 0 0 !important; bottom: 0 !important; cursor: sw-resize !important; left: 0 !important; }"));
		ownerDocument.getElementsByTagName("head")[0].appendChild(styleElement);

	};
	
	pub.areaDeselect = function(event) {

		if (event.button != 2) {

			if (!pub.areaMoving) {

				var xPosition = event.pageX;
				var yPosition = event.pageY;

				if (xPosition > pub.areaStartX) {

					pub.areaEndX = xPosition;

				} else {

					pub.areaEndX   = pub.areaStartX;
					pub.areaStartX = xPosition;

				};

				if (yPosition > pub.areaStartY) {

					pub.areaEndY = yPosition;

				} else {

					pub.areaEndY   = pub.areaStartY;
					pub.areaStartY = yPosition;

				};

			};

			pub.areaDrag   = false;
			pub.areaMoving   = false;
			pub.areaMoveX  = 0;
			pub.areaMoveY  = 0;
			pub.areaResize = false;

			pub.areaUpdateEnd();
			pub.areaUpdateStart();

		};

	};

	pub.areaDisplay = function() {

		var areaActualTab = getBrowser().mTabBox.selectedIndex;

		if (pub.areaSelectedTab==-1 || (pub.areaSelectedTab!=-1 && pub.areaSelectedTab != areaActualTab)) {

			var contentDocument = window.top.getBrowser().selectedBrowser.contentDocument;
			pub.areaUpdateEnd();
			pub.areaUpdateStart();
			pub.areaUpdateSize();

			pub.areaCreate(contentDocument);

			contentDocument.addEventListener("mousedown", pub.areaSelect, true);
			contentDocument.addEventListener("mousemove", pub.areaMove, false);
			contentDocument.addEventListener("mouseup", pub.areaDeselect, true);

			if (pub.areaSelectedTab!=-1) {

				var oldtab = gBrowser.getBrowserAtIndex(pub.areaSelectedTab);
				pub.areaRemove(oldtab.contentDocument);
			
			};

			gBrowser.tabContainer.addEventListener("TabSelect", pub.areaTabchange, false);
			gBrowser.tabContainer.addEventListener("TabClose", pub.areaTabchange, false);

			pub.areaSelectedTab = areaActualTab;

			document.getElementById("picsaveArea-toolbar").setAttribute("hidden",false);

		};

		pub.selectingArea = 1;

	};
	
	pub.areaTabchange = function(event) {

	    var selectedTab = getBrowser().mTabBox.selectedIndex;

		if (event.type=='TabClose' && pub.areaSelectedTab==selectedTab) {

			pub.areaRemove(window.top.getBrowser().selectedBrowser.contentDocument);

		} else {

			if(selectedTab != pub.areaSelectedTab) {

				document.getElementById("picsaveArea-toolbar").setAttribute("hidden",true);
				pub.selectingArea = 0;

			} else {

				document.getElementById("picsaveArea-toolbar").setAttribute("hidden",false);
				pub.selectingArea = 1;

			};

		};

	};

	pub.areaMove = function(event) {

		var element = event.target;

		if (element) {

			var ownerDocument = element.ownerDocument;

			if (ownerDocument) {

				var areaElement = ownerDocument.getElementById("picsaveArea");

				if (areaElement) {

					var xPosition = event.pageX;
					var yPosition = event.pageY;

					if (pub.areaDrag || pub.areaResize) {

						var height             = 0;
						var areaHeightElement = document.getElementById("picsaveArea-height");
						var areaWidthElement  = document.getElementById("picsaveArea-width");
						var width              = 0;

						pub.areaEndX = xPosition;
						pub.areaEndY = yPosition;

						if (pub.areaStartX > pub.areaEndX) {

							width = pub.areaStartX - pub.areaEndX;

							areaElement.style.left = xPosition + "px";

						} else {

							width = pub.areaEndX - pub.areaStartX;

							areaElement.style.left = pub.areaStartX + "px";

						};

						if (pub.areaStartY > pub.areaEndY) {

							height = pub.areaStartY - pub.areaEndY;

							areaElement.style.top = pub.areaEndY + "px";

						} else {

							height = pub.areaEndY - pub.areaStartY;

							areaElement.style.top = pub.areaStartY + "px";

						};

						areaElement.style.height = height + "px";
						areaElement.style.width  = width + "px";

						if (areaHeightElement) {

							areaHeightElement.value = height;

						};

						if (areaWidthElement) {

							areaWidthElement.value = width;

						};

					} else if (pub.areaMoving) {

						var newXPosition = xPosition - pub.areaMoveX;
						var newYPosition = yPosition - pub.areaMoveY;

						if (newXPosition < 0) {

							newXPosition = 0;

						};

						if (newYPosition < 0) {

							newYPosition = 0;

						};

						areaElement.style.left = newXPosition + "px";
						areaElement.style.top  = newYPosition + "px";
						pub.areaEndX   = newXPosition + areaElement.clientWidth;
						pub.areaStartX = newXPosition;
						pub.areaEndY   = newYPosition + areaElement.clientHeight;
						pub.areaStartY = newYPosition;

					};

					pub.areaUpdateEnd();
					pub.areaUpdateStart();

				};

			};

		};

	};

	pub.areaRemove = function(doc) {

		if (doc.getElementById("picsave-area-protector")) { doc.getElementById("picsave-area-protector").parentNode.removeChild(doc.getElementById("picsave-area-protector")); };
		if (doc.getElementById("picsaveArea")) { doc.getElementById("picsaveArea").parentNode.removeChild(doc.getElementById("picsaveArea")); };
		if (doc.getElementById("picsaveArea-styles")) { doc.getElementById("picsaveArea-styles").parentNode.removeChild(doc.getElementById("picsaveArea-styles")); };

		// document.getElementById("picsaveArea-toolbar").setAttribute("hidden",true);
		pub.areaSelectedTab = -1;

		try {
			doc.removeEventListener("mousedown", pub.areaSelect, true);
		} catch(exception) { };

		try {
			doc.removeEventListener("mousemove", pub.areaMove, false);
		} catch(exception) { };

		try {
			doc.removeEventListener("mouseup", pub.areaDeselect, true);
		} catch(exception) { };

		try {
			gBrowser.tabContainer.removeEventListener("TabSelect", pub.areaTabchange, false);
		} catch(exception) { };

		pub.selectingArea = 0;

	};

	pub.areaToolbarHidden = function() {		
		document.getElementById("picsaveArea-toolbar").setAttribute("hidden",true);

	};
	pub.areaSelect = function(event) {

		if (event.button != 2) {

			var element = event.target;

			if (element) {

				var elementName   = element.tagName;
				var ownerDocument = element.ownerDocument;

				if (elementName && elementName != "scrollbar" && ownerDocument) {

					var areaElement = ownerDocument.getElementById("picsaveArea");
					var xPosition    = event.pageX;
					var yPosition    = event.pageY;

					if (areaElement) {

						if (element == ownerDocument.getElementById("picsaveArea-container")) {

							pub.areaMoving  = true;
							pub.areaMoveX = xPosition - areaElement.offsetLeft;
							pub.areaMoveY = yPosition - areaElement.offsetTop;

						} else if (element == ownerDocument.getElementById("picsaveArea-north-east")) {

							pub.areaResize = true;
							pub.areaStartX = areaElement.offsetLeft;
							pub.areaStartY = areaElement.offsetTop + areaElement.clientHeight;

						} else if (element == ownerDocument.getElementById("picsaveArea-north-west")) {

							pub.areaResize = true;
							pub.areaStartX = areaElement.offsetLeft + areaElement.clientWidth;
							pub.areaStartY = areaElement.offsetTop + areaElement.clientHeight;

						} else if (element == ownerDocument.getElementById("picsaveArea-south-east")) {

							pub.areaResize = true;
							pub.areaStartX = areaElement.offsetLeft;
							pub.areaStartY = areaElement.offsetTop;

						} else if (element == ownerDocument.getElementById("picsaveArea-south-west")) {

							pub.areaResize = true;
							pub.areaStartX = areaElement.offsetLeft + areaElement.clientWidth;
							pub.areaStartY = areaElement.offsetTop;

						} else {

							pub.areaDrag   = true;
							pub.areaEndX   = 0;
							pub.areaEndY   = 0;
							pub.areaStartX = xPosition;
							pub.areaStartY = yPosition;

							pub.areaUpdateEnd();
							pub.areaUpdateStart();

						};

					};

				};

			};

			event.stopPropagation();
			event.preventDefault();

		};

	};

	pub.areaUpdateEnd = function() {

		var endXElement = document.getElementById("picsaveArea-end-x");
		var endYElement = document.getElementById("picsaveArea-end-y");

		if (endXElement) {

			endXElement.value = pub.areaEndX;

		};

		if (endYElement) {

			endYElement.value = pub.areaEndY;

		};

	};

	pub.areaUpdateHeight = function(element) {

		var height       = element.value;

		var areaElement = window.top.getBrowser().selectedBrowser.contentDocument.getElementById("picsaveArea");

		if (areaElement) {

			height                    = parseInt(height);
			areaElement.style.height = height + "px";
			pub.areaEndY    = pub.areaStartY + height;

			pub.areaUpdateEnd();

		};

	};

	pub.areaUpdateStart = function() {

		var startXElement = document.getElementById("picsaveArea-start-x");
		var startYElement = document.getElementById("picsaveArea-start-y");

		if (startXElement) {

			startXElement.value = pub.areaStartX;

		};

		if (startYElement) {

			startYElement.value = pub.areaStartY;

		};

	};

	pub.areaUpdateSize = function() {

		var width              = 0;
		var height             = 0;
		var areaWidthElement  = document.getElementById("picsaveArea-width");
		var areaHeightElement = document.getElementById("picsaveArea-height");

		if (pub.areaStartX > pub.areaEndX) {

			width = pub.areaStartX - pub.areaEndX;

		} else {

			width = pub.areaEndX - pub.areaStartX;

		};

		if (pub.areaStartY > pub.areaEndY) {

			height = pub.areaStartY - pub.areaEndY;

		} else {

			height = pub.areaEndY - pub.areaStartY;

		};

		areaWidthElement.value = width;
		areaHeightElement.value = height;

	};

	pub.areaUpdateWidth = function(element) {

		var width        = element.value;

		var areaElement = window.top.getBrowser().selectedBrowser.contentDocument.getElementById("picsaveArea");

		if (areaElement) {

			width                    = parseInt(width);
			areaElement.style.width = width + "px";
			pub.areaEndX   = pub.areaStartX + width;

			pub.areaUpdateEnd();

		};

	};

	pub.areaCapture = function() {
		pub.areaRemove(window.top.getBrowser().selectedBrowser.contentDocument);
		pub.capture(window.content,pub.areaStartX,pub.areaStartY,pub.areaEndX-pub.areaStartX,pub.areaEndY-pub.areaStartY);
		setTimeout(function(){
			pub.areaToolbarHidden();		
		},500);

	};
	
	pub.settings = function() {
		window.openDialog("chrome://picsave/content/picsaveSettings.xul", "picsave-settings-dialog", "centerscreen,chrome,modal,resizable");
	};
	
	pub.init = function() {

		pub.bundle = pub.srGetStrBundle("chrome://picsave/locale/picsave.properties");
		pub.uploadingTitle = pub.bundle.GetStringFromName("uploadingTitle");
		pub.dimensions = pub.bundle.GetStringFromName("dimensions");
		pub.filesize = pub.bundle.GetStringFromName("filesize");
		pub.apiUrl = pub.bundle.GetStringFromName("apiUrl");
		pub.apiDomain = pub.bundle.GetStringFromName("apiDomain");
// alert(pub.apiDomain);
		pub.contextMenuLoad();

	};
	
	return pub;
	
}();

	window.addEventListener("load", com.aardvarkPicsave.tools.init, false);